package com.starlz.jpa.service.impl;

import com.starlz.jpa.dao.UserDao;
import com.starlz.jpa.entity.LocalRole;
import com.starlz.jpa.entity.LocalUser;
import com.starlz.jpa.service.LocalUserDetilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: wangzi
 * @Date: 2018/11/20 14:11
 */
@Service("localUserDetilService")
public class LocalUserDetilServiceImpl implements LocalUserDetilService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LocalUser localUser = userDao.findByUsername(username);

        if (localUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        User user = new User(localUser.getUsername(), localUser.getPassword(), getRoles(localUser.getRoles()));

        return user;
    }

    private List getRoles(List<LocalRole> roles){

        ArrayList<Object> list = new ArrayList<>();

        for (LocalRole role : roles){
            list.add(role.getRoleName());
        }

        return list;
    }
}
